var fs = require('fs');
var config = require('./config.json');
var path = require('path');
var simpleGit = require('simple-git')(config.workspace.gitolite.gitolite_repo);
var logger = require('log4js').getLogger();
var readline = require('readline');
var waterfall = require('async-waterfall');
//var workspace_dirs = require('./dirs').workspace_dirs;
var request = require('request');

exports.cloneGitRepository = function (git_name, local_path, call_back) {
    cloneGit(git_name, local_path, "develop", function (err, data) {
        if (err) {
            logger.error(err);
            return call_back(err);
        }
        logger.info("clone项目成功");
        call_back(null, "done");
    });
};

/**
 * 删除项目对应的gitolite库
 * @param git_name
 * @param call_back
 */
//exports.removeGit = function (git_name, call_back) {
//    var git_server = "http://" + config.git_server.host + ":" + config.git_server.port + "/api/git/remove";
//    //调用git-server创建git库
//    request.post({
//        url: git_server,
//        form: {project_name: git_name}
//    }, function (err, req) {
//        if (err) {
//            logger.error(err);
//            logger.error("调用git服务出错");
//            return call_back(err);
//        }
//        logger.info(req.body);
//        if (req.body.code == "500") {
//            logger.error(res.msg);
//            return call_back(res.msg);
//        }
//        logger.info("git服务删除git库成功");
//        call_back(null,"done");
//    });
//}

//exports.checkGitUrl = function (req, res, next) {
//    var repoPath = req.body.git_url;
//    var git_source = req.body.git_source;
//    if (git_source == "0") {
//        return res.format_json(null, 200, "success");
//    }
//    if (!_.startsWith(repoPath, config.workspace.gitolite.repo_pre)) {
//        return res.format_json(null, 401, "failed");
//    }
//    simpleGit.listRemote([repoPath], function (err, data) {
//        if (err) {
//            return res.format_json(null, 400, "failed");
//        }
//        return res.format_json(null, 200, "success");
//    });
//}
var cloneGit = function (git_name, localPath, branch, call_back) {
    var Repository = require('git-cli').Repository;
    var repoPath = config.workspace.gitolite.repo_pre + git_name;
    //repoPath = "git@123.56.190.188:TZJC";
    Repository.clone(repoPath, localPath, {branch: branch}, function (err, data) {
        if (err) {
            logger.error(err);
            logger.error("clone项目失败");
            return call_back(err);
        }
        console.log(data);
        call_back(null, data);
    });
};
exports.cloneGit = cloneGit;
exports.pullGit = function (path, remote, branch, call_back) {
    var simpleGit = require('simple-git')(path);
    simpleGit.pull(remote, branch, call_back);
}